package com.lingshu.app.messaging;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.lingshu.app.R;
import com.lingshu.app.config.App;
import com.lingshu.app.config.Constants;
import com.lingshu.core.utils.KLog;
import com.lingshu.app.ui.main.MainActivity;
import com.lingshu.app.utils.JsonUtils;
import com.lingshu.app.utils.RabbitMQUtils;
import com.lingshu.core.eventbus.EventBusManager;
import com.lingshu.core.eventbus.EventData;
import com.lingshu.core.eventbus.EventKey;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

public class ReceiveMessageService extends Service {
    private final String TAG = this.getClass().getSimpleName();
    private final String EXCHANGE_NAME = "ls.screening.shift.receive";
    private static final String CHANNEL_ID = "my_channel_id";
    private static final int NOTIFICATION_ID = 1;
    private Connection connection;
    private Channel channel;
    private NotificationManager notificationManager;

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(NOTIFICATION_ID, getNotification("聆己系统启动，准备接收数据"));
        receiveMessage();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 接收队列消息
     */
    private void receiveMessage() {
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(() -> {
            //接收MQ消息
            try {
                connection = RabbitMQUtils.getConnection();
                channel = RabbitMQUtils.getChannel(connection);
            } catch (IOException e) {
                KLog.e(TAG, e.getMessage());
            } catch (TimeoutException e) {
                KLog.e(TAG, e.getMessage());
            }

            try {
                RabbitMQUtils.receiveMessage(channel, EXCHANGE_NAME, message -> {
                    Long currentUserId = App.getMvUtils().getLong(Constants.USER_ID);
                    ShiftMessageObject messageObject = JsonUtils.fromJson(message, ShiftMessageObject.class);
                    if (messageObject != null && currentUserId.equals(messageObject.getDoctorId())) {
                        showNotification("有报告需要处理");
                        EventBusManager.post(new EventData<>(EventKey.Refresh, "refresh"));
                    }
                });
            } catch (Exception e) {
                KLog.e(TAG, e.getMessage());
            }
        });
    }

    /**
     * 创建channel
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "推送通知";
            String description = "优先提醒";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);
            channel.canBypassDnd();//是否可以绕过请勿打扰模式
            channel.canShowBadge();//是否可以显示icon角标
            channel.enableLights(true);//是否显示通知闪灯
            channel.enableVibration(true);//收到小时时震动提示
            channel.setBypassDnd(true);//设置绕过免打扰
            channel.setLockscreenVisibility(-1000);
            channel.setLightColor(Color.RED);//设置闪光灯颜色
            channel.getAudioAttributes();//获取设置铃声设置
            channel.setVibrationPattern(new long[]{100, 200, 100});//设置震动模式
            channel.shouldShowLights();//是否会闪光
            channel.setDescription(description);

            if (notificationManager == null)
                notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(channel);
        }
    }

    /**
     * 生成 notification
     *
     * @param contentText
     * @return
     */
    private Notification getNotification(String contentText) {
        //点击进入会话
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_MUTABLE);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        builder.setSmallIcon(R.drawable.icon);
        builder.setContentTitle("消息通知");
        builder.setContentText(contentText);
        builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
        builder.setContentIntent(pendingIntent);
        builder.setAutoCancel(false);
        return builder.build();
    }

    /**
     * @param message
     */
    private void showNotification(String message) {
        Notification notification = getNotification(message);
        if (notificationManager == null)
            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, notification);
    }
}
